package com.alibaba.nacos.config.server.jpa.aspect;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-11
 */
public abstract class AbstractPersistServiceAspect {

    protected Map<MethodInfo,Method> map = new HashMap<>();

    protected void init(Class<?> clazz){
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
            String methodName = declaredMethod.getName();
            MethodInfo methodInfo = new MethodInfo(methodName, parameterTypes);
            map.put(methodInfo, declaredMethod);
        }
    }

    protected Object proceed(ProceedingJoinPoint joinPoint, Object targetBean) throws Throwable {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Class[] parameterTypes = signature.getParameterTypes();
        Object[] args = joinPoint.getArgs();
        Method method = signature.getMethod();

        String methodName = method.getName();

        MethodInfo methodInfo = new MethodInfo(methodName, parameterTypes);

        Method targetMethod = map.get(methodInfo);

        if (Objects.nonNull(targetMethod)) {
            return targetMethod.invoke(targetBean, args);
        }

        return joinPoint.proceed();
    }

}
